package com.zk.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.zk.yygh.oss.service.OSSService;
import com.zk.yygh.oss.utils.ConstantOssPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author: 张凯
 * @date: 2022/6/17 - 9:55
 */
@Service
public class OSSServiceImpl implements OSSService {
    @Override
    public String fileUpLoad(MultipartFile file) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = ConstantOssPropertiesUtils.EDNPOINT;
        String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantOssPropertiesUtils.SECRECT;
        String bucketName = ConstantOssPropertiesUtils.BUCKET;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //获取上传文件流
        try {
            InputStream inputStream = file.getInputStream();
            //获取上传的文件名
            String fileName = file.getOriginalFilename();
            //生成随机的uuid
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //获取当前的时间生成目录
            String dateTime = new DateTime().toString("yyyy/MM/dd");
            //拼接对应的存储目录
            String fileUrl=dateTime+"/"+uuid+fileName;
            //上传文件：相同的文件名重复上传会被覆盖
            ossClient.putObject(bucketName, fileUrl, inputStream);
            //拼接对应的url
            String url="https://"+bucketName+"."+endpoint+"/"+fileUrl;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            //关闭OSSClient实例
            ossClient.shutdown();
            return null;
        }
    }
}
